package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IRegionService regionService;
    @Override
    public void insert(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);

    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).get();
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //查询条件
        Query query = new Query();
        //count 总条数
        long count = template.count(query, Region.class);
        if (count == 0) {
            return Page.empty();
        }
        //list当前页数据
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> list = template.find(query, Region.class);

        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())){
            this.update(region);
        }else {
            this.insert(region);
        }
    }

    @Override
    //区域热门修改
    public void changeHotValue(int hot, String id) {
       /* //查询
        Region region = regionService.get(id);
        //替换
        region.setIshot(hot);
        //更新
        regionService.update(region);*/
        //方法2
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,Region.class);


    }

    @Override
    //前端目的地热门区域
    public List<Region> queryHotRegion() {
        //状态热门的排序
        return regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
